// 担保支付
// 实现逻辑：调用后台接口，获取到一个订单号，然后拿着这个订单号和appid请求https://developer.toutiao.com/api/apps/ecpay/v1/create_order
// 在接口返回 order_id 和 order_token 之后 再通过tt.pay唤起收银台，用户支付结果会在success和fail中体现

// 非担保支付
// 实现逻辑：调用后端接口，返回data 和 byteAuthorization，然后调用requestOrder API 拿到 orderId  ，在拿到orderId 之后在调用 getOrderPayment 方法唤起支付
// 这个api的回调会返回 orderId 这个是抖音开放平台内部的交易订单号 

import {
  orderCreate
} from '@/api/pay.js'
import storage from "@/utils/storage.js";


export function ttPay({
  gameId,
  payScene = 'diamond',
  doyinImId,
  iosBackPercent
}) {

  return new Promise((resolve, reject) => {
    uni.showLoading({
      title: "检测支付环境...",
    });
    let systemInfo = uni.getSystemInfoSync()
    let launchOption = storage.getLaunchOption()
    orderCreate({
      gameId,
      platform: systemInfo.platform,
      phoneType: systemInfo.deviceModel,
      payScene: payScene,
      adid: launchOption.query.adid || launchOption.query.ad_params && launchOption.query
        .ad_params.ad_id || ''
    }).then(res => {
      // resolve(res)
      if (res.data.success) {
        let {
          data,
          byteAuthorization,
          orderId
        } = res.data.result
        let resOrderId = orderId

        let isCanuse = tt.canIUse('requestOrder')

        if (isCanuse) {

          uni.requestOrder({
            data: data,
            byteAuthorization: byteAuthorization,
            success: (res) => {
              let {
                orderId
              } = res
              uni.hideLoading()


              let PaymentPayload

              if (systemInfo.platform == 'ios') {
                PaymentPayload = {
                  orderId: orderId,
                  // #ifdef MP-TOUTIAO
                  imId: doyinImId,
                  immediate: true
                  // #endif
                }
              } else {
                PaymentPayload = {
                  orderId: orderId
                }
              }

              uni.getOrderPayment({
                ...PaymentPayload,

                success: (res) => {
                  resolve({
                    successData: res,
                    resOrderId
                  })
                  console.log('走成功')
                },
                fail: (err) => {
                  reject({
                    errData: err,
                    resOrderId
                  })
                  console.log('走失败')
                }
              })
            },
            fail: (err) => {
              console.error(err, 'requestOrder-----------------')
              reject({
                errData: err,
                resOrderId
              })
              uni.hideLoading()
            },
          })
        } else {
          reject({
            errData: "当前抖音版本过低，请先更新",
            resOrderId
          })
          uni.hideLoading()
        }

      } else {
        reject({
          errData: "请求失败",
          resOrderId: ""
        })
        uni.hideLoading()
      }
    }).catch(err => {
      uni.hideLoading()
    })
  })

}